<template>
  <div
    class="chatPage container h-[calc(100vh-3rem)] bg-gradient-to-r from-blue-100 to-green-100"
  >
    <!-- 顶部 -->
    <div
      class="chat-header h-[calc(10vh)] w-full flex items-center justify-center px-4"
    >
      <h2 class="text-cyan-700">AI 穿搭</h2>
    </div>

    <!-- 聊天记录 -->
    <div class="chat_wrapper h-[calc(72vh)] overflow-y-auto mx-auto p-4 z-1">
      <div
        v-for="(item, index) in msgController"
        :key="index"
        class="chat-item w-full"
      >
        <component
          :is="item.type === 1 ? AIReply : UserQuery"
          :msg="item.content"
        />
      </div>
    </div>

    <!-- 底部提问栏 -->
    <div
      class="chat_footer h-16 w-full bottom-0 absolute z-999 flex items-center justify-center"
    >
      <div class="absolute -top-6" v-show="showSugget">
        <button
          @click="sugget"
          class="border-2 border-gray-300 rounded text-white-500 text-xs bg-white px-4 py-2"
        >
          {{ suggetMsg }}
        </button>
      </div>
      <van-search
        v-model="searchField"
        placeholder="请输入搜索关键字"
        show-action
        shape="round"
        background="transparent"
        class="py-2 w-[90%]"
        v-if="!isGenerating"
      >
        <template #action>
          <div class="text-white">
            <van-icon
              name="guide-o"
              class="text-blue-500"
              size="1.25rem"
              @click="handleChat"
            />
          </div>
        </template>
      </van-search>
      <van-loading vertical v-else>
        <template #icon>
          <van-icon name="star-o" size="30" color="blue" />
        </template>
      </van-loading>
    </div>

    <!-- 过场动画 遮蔽层-->
    <Transition v-show="showShadow" name="slide">
      <div
        class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-80"
      >
        <div class="text-white text-3xl font-bold">Loading...</div>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import UserQuery from "../../components/ChatAI/UserQuery.vue";
import AIReply from "../../components/ChatAI/AIReply.vue";
import { sentMsg, getMsg, queryMsgCompleted } from "../../api/msg";
import { handleAIResult } from "../../api/handle";

// 类型定义
type msgItem = {
  type: number; // 1:AI 2:用户
  content: string;
};

// 响应式变量
const searchField = ref("");
const showShadow = ref(true);
const isGenerating = ref(false);
const showSugget = ref(false);
const suggetions = ref<any>([]);
const suggetMsg = ref("");
const msgController = ref<msgItem[]>([
  {
    type: 1,
    content:
      "欢迎来到我的穿搭世界！我是一个热爱时尚的小助手，很高兴能为您提供穿搭建议。",
  },
]);

// 定时关闭遮蔽层
setTimeout(() => (showShadow.value = false), 100);

// 发送消息
const handleChat = async () => {
  if (searchField.value.length > 0) {
    try {
      isGenerating.value = true;
      showSugget.value = false;

      const msg = searchField.value;
      addMessageToController(2, msg);
      searchField.value = "";

      addMessageToController(1, "努力搭配中...");

      const res = await sentMsg(msg);
      const { conversation_id, id } = res.data;

      await queryMsgCompleted(conversation_id, id, 2000);
      const msgList = await getMsg(conversation_id, id);
      const classifyMsg = handleAIResult(msgList.data);

      msgController.value.pop(); // Remove "努力搭配中..." message
      msgController.value.push(...classifyMsg.answer);

      showSugget.value = true;
      suggetions.value = classifyMsg.follow_up;
      suggetMsg.value = suggetions.value[0];
    } catch (err) {
      handleError(err);
    } finally {
      isGenerating.value = false;
    }
  }
};

// 添加消息到消息控制器
const addMessageToController = (type: number, content: string) => {
  msgController.value.push({ type, content });
};

// 错误处理
const handleError = (err: any) => {
  msgController.value.pop();
  msgController.value.push({ type: 1, content: "🔗啊哦！网络不可用(｡•ˇ‸ˇ•｡)" });
  console.error(err);
};

// 建议处理
const sugget = () => {
  searchField.value = suggetMsg.value;
  suggetions.value.shift();
  suggetMsg.value = suggetions.value[0];

  if (suggetions.value.length === 0) {
    showSugget.value = false;
  }
};
</script>

<style lang="less" scoped>
.chatPage {
  position: relative;
}

.chat-header {
  background-color: rgba(255, 255, 255, 0.1);
}

.chat_wrapper {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
}

.chat_footer {
  background-color: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.slide-enter-active,
.slide-leave-active {
  transition: opacity 0.3s ease;
}

.slide-leave-to {
  opacity: 0;
}
</style>
